package dgdb2d;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Random;

/**
 * @author Pawel Bulwan
 * 
 */
public class RandomServerManager implements ServerManager {

	ArrayList<ServerDescriptor> serverList = null;

	@Override
	public RemoteGraph getDestinationServer() {
		// konstrukcja listy serwerow na podstawie mapy znanych serwerow
		this.init();

		// brak dostepnych serwerow
		if ((serverList == null) || (serverList.isEmpty()))
			return null;

		// wybor serwera
		Random generator = new Random();
		int randomIndex = generator.nextInt(serverList.size());
		ServerDescriptor sd = serverList.get(randomIndex);

		System.out.println("Choosing backup server #" + randomIndex + " (ip = " + sd.Address.getHostString() + ")");

		return sd.GraphReference;

	}

	/**
	 * Inicjalizacja.
	 */
	private void init() {
		serverList = new ArrayList<ServerDescriptor>();

		// pobranie mapy serwerow serwera lokalnego
		GraphDataBase gdb = GraphDataBase.getInstance();
		HashMap<InetSocketAddress, RemoteGraph> servers = gdb.serverMap;

		// konwersja mapy do listy
		Iterator<Entry<InetSocketAddress, RemoteGraph>> it = servers.entrySet().iterator();

		while (it.hasNext()) {
			// iteracja po elementach
			Entry<InetSocketAddress, RemoteGraph> pairs = it.next();
			// dodanie wpisu
			ServerDescriptor sd = new ServerDescriptor(pairs.getKey(), pairs.getValue());
			serverList.add(sd);
		}
	}

	/**
	 * Klasa wewnetrza opisujaca potencjalny serwer zapasowy.
	 */
	class ServerDescriptor {

		InetSocketAddress Address;
		RemoteGraph GraphReference;

		public ServerDescriptor(InetSocketAddress addr, RemoteGraph rgraph) {
			Address = addr;
			GraphReference = rgraph;
		}
	}

}
